home *** CD-ROM | disk | FTP | other *** search
- Path: news.bridge.net!news
- From: David Byrden <100101.2547@compuserve.com>
- Newsgroups: comp.lang.c++
- Subject: Re: STL
- Date: 23 Feb 1996 08:49:06 GMT
- Organization: self-employed
- Message-ID: <4gjv22$4i1@news.bridge.net>
- References: <4gdgt0$494@netaxs.com>
- NNTP-Posting-Host: ppp-mia1-63.bridge.net
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 1.1N (Windows; I; 16bit)
-
-
- >>>
- class myclass
- {
- int myint;
- float myfloat;
-
- };
- >>>
-
- >> I want use "list" and stuff a bunch of these in using push_back. No
- >> problem so far. But I want the user to be able to select which item
- >> to sort on... myint or myfloat
-
-
- Whose compiler and whose STL are you using? The List class is supposed
- to have a sort member function which is templated. HP's STL does not
- provide it because few compilers can support template member functions
- (if any?)
-
-
- You need to use a container where you can do sorts with a templated
- functor. The sort algorithm itself has a suitable version but it requires
- random access iterators, so that rules out "list".
-
-
- Once you can sort with a templated functor, you need to write a couple
- of functors to go with your class, one of which compares the objects'
- ints, and the other of which compares their floats. These functors don't
- need any data attached, so they can be functions.
-
-
- Here we go;
-
-
- inline bool intCompare( const myclass& lhs, const myclass& rhs )
- {
- return lhs.myint < rhs.myint ;
- }
-
-
- vector< myclass > myThings;
-
- sort( myThings.begin(), myThings,end(), intCompare ) ;
-
-
- See?
-
-
- David
-
-
-
-